<template>
  <div class="sole-fusion-container">
    <div class="fusion-content">
      <div class="left-panel">
        <!-- Step 1 -->
        <div class="step-section" :class="{ 'active-step': currentStep === 1 }">
          <div class="step-header" @click="setStep(1)">
            <span class="step-title">Step 1</span>
            <span class="step-desc">上传鞋底的鞋款</span>
            <el-tooltip content="帮助信息" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
            <span v-if="mainImage" class="step-status">
              <el-icon><Check /></el-icon>
            </span>
          </div>

          <div class="upload-section">
            <div class="image-preview" @click="handleMainUploadClick">
              <div v-if="mainImage" class="preview-container">
                <img :src="mainImage" alt="鞋面图预览" class="preview-img" />
                <div class="change-overlay">
                  <el-icon><Plus /></el-icon>
                  <span>更换图片</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <span>点击上传图片</span>
              </div>
              <input ref="fileInputMain" type="file" accept="image/*" style="display:none" @change="handleMainFileSelect" />
            </div>

            <!-- 添加标记可选区域按钮 -->
            <div
              v-if="mainImage"
              class="mark-area"
              @click="showSelectionOptions(1)"
            >
              <el-icon><EditPen /></el-icon>
              <span>标记可选区域</span>
            </div>
          </div>
        </div>

        <!-- Step 2 -->
        <div class="step-section" :class="{ 'active-step': currentStep === 2 }" style="margin-top: 30px;">
          <div class="step-header" @click="setStep(2)">
            <span class="step-title">Step 2</span>
            <span class="step-desc">上传鞋面的鞋款</span>
            <el-tooltip content="帮助信息" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
            <span v-if="referenceImage" class="step-status">
              <el-icon><Check /></el-icon>
            </span>
          </div>

          <div class="upload-section">
            <div class="image-preview" @click="handleReferenceUploadClick">
              <div v-if="referenceImage" class="preview-container">
                <img :src="referenceImage" alt="鞋底图预览" class="preview-img" />
                <div class="change-overlay">
                  <el-icon><Plus /></el-icon>
                  <span>更换图片</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <span>点击上传图片</span>
              </div>
              <input ref="fileInputReference" type="file" accept="image/*" style="display:none" @change="handleReferenceFileSelect" />
            </div>

            <!-- 添加标记可选区域按钮 -->
            <div
              v-if="referenceImage"
              class="mark-area"
              @click="showSelectionOptions(2)"
            >
              <el-icon><EditPen /></el-icon>
              <span>标记可选区域</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间工作区域 -->
      <div class="work-area">
        <template v-if="!mainImage && !referenceImage">
          <div class="instructions-container">
            <div class="instructions-content">
              <h3>使用说明</h3>
              <ol>
                <li>请上传背景干净无杂物的产品图，单只鞋的正面图最佳</li>
                <li>请尽量保持主产品与参考图两款鞋子角度一致性以达到最佳生成效果</li>
                <li>在参数调整中，可以选择不同的蒙版状态来获得不同的效果</li>
              </ol>
            </div>
          </div>
        </template>

        <!-- 主内容区的图片工作区只在没有弹窗时显示 -->
        <div v-if="!editModalVisible && !uploadModalVisible && !isViewingResults">
          <!-- 显示主图或参考图工作区，只能显示一个 -->
          <Suspense v-if="isEditingMainImage">
            <template #default>
              <div class="image-workspace-container">
                <ImageWorkspaceComp
                  :image-url="mainImage"
                  :original-image-name="mainImageName"
                  @image-edited="handleMainImageEdited"
                  @editing-completed="completeStep(1)"
                  ref="mainImageWorkspaceRef"
                />
              </div>
            </template>
            <template #fallback>
              <div class="loading-state">
                <el-icon class="loading-icon"><Loading /></el-icon>
                <p>加载中...</p>
              </div>
            </template>
          </Suspense>
          <Suspense v-else-if="isEditingReferenceImage">
            <template #default>
              <div class="image-workspace-container">
                <ImageWorkspaceComp
                  :image-url="referenceImage"
                  :original-image-name="referenceImageName"
                  @image-edited="handleReferenceImageEdited"
                  @editing-completed="completeStep(2)"
                  ref="referenceImageWorkspaceRef"
                />
              </div>
            </template>
            <template #fallback>
              <div class="loading-state">
                <el-icon class="loading-icon"><Loading /></el-icon>
                <p>加载中...</p>
              </div>
            </template>
          </Suspense>
        </div>

        <!-- 结果查看区域 -->
        <Suspense v-if="isViewingResults">
          <template #default>
            <div class="image-workspace-container">
              <ImageWorkspaceComp
                :image-url="mainImage"
                :original-image-name="mainImageName"
                :is-view-results="true"
                :result-images="generatedImages"
                @image-edited="handleResultSelected"
                @exit-results="exitResultsView"
                ref="resultsWorkspaceRef"
                crossorigin="anonymous"
              />
            </div>
          </template>
          <template #fallback>
            <div class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>加载中...</p>
            </div>
          </template>
        </Suspense>
       
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 生成按钮 -->
        <el-button 
          type="primary" 
          class="generate-btn" 
          @click="handleGenerate"
          :disabled="!canGenerate"
        >
          立即生成
        </el-button>

        <div class="nav-buttons">
          <el-button v-if="currentStep > 1" @click="prevStep">
            上一步
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主图本地预览弹窗 -->
    <el-dialog 
      v-model="showPreviewDialogMain" 
      title="主图预览" 
      width="800px" 
      :close-on-click-modal="false"
      @close="cancelMainPreview"
    >
      <div class="upload-modal-content">
        <div class="upload-area">
          <div v-if="previewImageMain" class="file-preview">
            <img :src="previewImageMain" alt="主图预览" class="preview-img" />
          </div>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <span>请先选择图片</span>
            <p class="upload-tip">支持 JPG、PNG 格式，最大 10MB</p>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelMainPreview">取消</el-button>
          <el-button type="primary" @click="confirmMainPreview" :disabled="!selectedFileMain">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 副图本地预览弹窗 -->
    <el-dialog 
      v-model="showPreviewDialogReference" 
      title="副图预览" 
      width="800px" 
      :close-on-click-modal="false"
      @close="cancelReferencePreview"
    >
      <div class="upload-modal-content">
        <div class="upload-area">
          <div v-if="previewImageReference" class="file-preview">
            <img :src="previewImageReference" alt="副图预览" class="preview-img" />
          </div>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <span>请先选择图片</span>
            <p class="upload-tip">支持 JPG、PNG 格式，最大 10MB</p>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelReferencePreview">取消</el-button>
          <el-button type="primary" @click="confirmReferencePreview" :disabled="!selectedFileReference">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 主图编辑弹窗 -->
    <el-dialog v-model="showEditDialogMain" title="主图编辑" width="50%" :close-on-click-modal="false" class="edit-dialog">
      <div class="edit-modal-content">
        <Suspense>
          <template #default>
            <div class="image-workspace-container">
              <ImageWorkspaceComp
                :image-url="mainImage"
                :original-image-name="mainImageName"
                @image-edited="handleMainImageEdited"
                @editing-completed="closeEditDialogMain"
              />
            </div>
          </template>
          <template #fallback>
            <div class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>加载中...</p>
            </div>
          </template>
        </Suspense>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeEditDialogMain">取消</el-button>
          <!-- <el-button type="primary" @click="closeEditDialogMain">确认编辑</el-button> -->
        </div>
      </template>
    </el-dialog>

    <!-- 副图编辑弹窗 -->
    <el-dialog v-model="showEditDialogReference" title="副图编辑" width="50%" :close-on-click-modal="false" class="edit-dialog">
      <div class="edit-modal-content">
        <Suspense>
          <template #default>
            <div class="image-workspace-container">
              <ImageWorkspaceComp
                :image-url="referenceImage"
                :original-image-name="referenceImageName"
                @image-edited="handleReferenceImageEdited"
                @editing-completed="closeEditDialogReference"
              />
            </div>
          </template>
          <template #fallback>
            <div class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>加载中...</p>
            </div>
          </template>
        </Suspense>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeEditDialogReference">取消</el-button>
          <!-- <el-button type="primary" @click="closeEditDialogReference">确认编辑</el-button> -->
        </div>
      </template>
    </el-dialog>

    <!-- 标记可选区域选项弹窗 -->
    <SelectionOptionsDialog
      v-model="showSelectionDialog"
      @select="handleSelectOption"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, defineAsyncComponent, computed } from "vue";
import {
  Plus,
  Loading,
  QuestionFilled,
  Check,
  EditPen,
} from "@element-plus/icons-vue";
// Import the component
const SelectionOptionsDialog = defineAsyncComponent(
  () => import("../common/SelectionOptionsDialog.vue")
);
import type { UploadInstance } from "element-plus";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import {
  uploadImage,
  feedbackImage,
  isUserLoggedIn,
  xdhh,
} from "../../api/file";
import type {
  UploadImageResponse,
  XdhhRequest,
  XdhhResponse,
} from "../../api/file";
import { useRouter } from "vue-router";

// 引入异步组件
const ImageWorkspaceComp = defineAsyncComponent(
  () => import("./ImageWorkspace.vue")
);

// 获取路由器
const router = useRouter();

// 步骤状态管理
const currentStep = ref(1);
const mainImageWorkspaceRef = ref<any>(null);
const referenceImageWorkspaceRef = ref<any>(null);

// 主图相关状态
const showPreviewDialogMain = ref(false);
const previewImageMain = ref('');
const selectedFileMain = ref<File|null>(null);
const showEditDialogMain = ref(false);
const mainImage = ref('');
const mainImageName = ref('');
const mainImageId = ref<number | null>(null);
const fileInputMain = ref<HTMLInputElement | null>(null);

// 副图相关状态
const showPreviewDialogReference = ref(false);
const previewImageReference = ref('');
const selectedFileReference = ref<File|null>(null);
const showEditDialogReference = ref(false);
const referenceImage = ref('');
const referenceImageName = ref('');
const referenceImageId = ref<number | null>(null);
const fileInputReference = ref<HTMLInputElement | null>(null);

// 状态管理
const maskStates = ref(3);

// 添加编辑状态变量
const isEditingMainImage = ref(false);
const isEditingReferenceImage = ref(false);
const editModalVisible = ref(false);
const uploadModalVisible = ref(false);

// 结果查看相关
const isViewingResults = ref(false);
const generatedImages = ref<string[]>([]);
const resultsWorkspaceRef = ref<any>(null);

// 添加标记选项状态变量
const showSelectionDialog = ref(false);
const currentMarkStep = ref(1);

// 计算属性
const canGenerate = computed(() => {
  return (
    !!mainImage.value &&
    !!referenceImage.value &&
    mainImageId.value !== null &&
    referenceImageId.value !== null
  );
});

// 步骤控制方法
const setStep = (step: number) => {
  if (step === 1 || (step === 2 && mainImage.value)) {
    currentStep.value = step;
  }
};

const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value -= 1;
  }
};

// 主图上传
const handleMainUploadClick = () => {
  fileInputMain.value?.click();
};

const handleMainFileSelect = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (file) {
    selectedFileMain.value = file;
    const reader = new FileReader();
    reader.onload = e => {
      previewImageMain.value = e.target?.result as string;
      showPreviewDialogMain.value = true;
      uploadModalVisible.value = true;
    };
    reader.readAsDataURL(file);
  }
};

const confirmMainPreview = () => {
  if (!selectedFileMain.value) return;
  uploadFile(selectedFileMain.value, 'input', (_, imageId) => {
    if (imageId) mainImageId.value = typeof imageId === 'number' ? imageId : parseInt(imageId as string, 10);
    mainImageName.value = imageId?.toString() || '';
    showEditDialogMain.value = true;
    editModalVisible.value = true;
  });
  mainImage.value = previewImageMain.value;
  showPreviewDialogMain.value = false;
  uploadModalVisible.value = false;
  // 清空文件输入框
  if (fileInputMain.value) {
    fileInputMain.value.value = '';
  }
  selectedFileMain.value = null;
  previewImageMain.value = '';
  
  // 如果两张图片都上传完成，自动进入第2步
  if (mainImage.value && referenceImage.value && mainImageId.value !== null && referenceImageId.value !== null) {
    currentStep.value = 2;
  }
};

// 副图上传
const handleReferenceUploadClick = () => {
  fileInputReference.value?.click();
};

const handleReferenceFileSelect = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (file) {
    selectedFileReference.value = file;
    const reader = new FileReader();
    reader.onload = e => {
      previewImageReference.value = e.target?.result as string;
      showPreviewDialogReference.value = true;
      uploadModalVisible.value = true;
    };
    reader.readAsDataURL(file);
  }
};

const confirmReferencePreview = () => {
  if (!selectedFileReference.value) return;
  uploadFile(selectedFileReference.value, 'input', (_, imageId) => {
    if (imageId) referenceImageId.value = typeof imageId === 'number' ? imageId : parseInt(imageId as string, 10);
    referenceImageName.value = imageId?.toString() || '';
    showEditDialogReference.value = true;
    editModalVisible.value = true;
  });
  referenceImage.value = previewImageReference.value;
  showPreviewDialogReference.value = false;
  uploadModalVisible.value = false;
  // 清空文件输入框
  if (fileInputReference.value) {
    fileInputReference.value.value = '';
  }
  selectedFileReference.value = null;
  previewImageReference.value = '';
  
  // 如果两张图片都上传完成，自动进入第2步
  if (mainImage.value && referenceImage.value && mainImageId.value !== null && referenceImageId.value !== null) {
    currentStep.value = 2;
  }
};

// 上传文件到服务器
function uploadFile(file: File, type: "input" | "output", callback?: (imageUrl: string, imageId?: number | string) => void) {
  if (!isUserLoggedIn()) {
    ElMessageBox.confirm(
      "您需要登录才能上传图片。是否现在登录？",
      "未登录提示",
      {
        confirmButtonText: "去登录",
        cancelButtonText: "取消",
        type: "warning",
      }
    ).then(() => {
      localStorage.setItem("redirectAfterLogin", router.currentRoute.value.fullPath);
      router.push("/login");
    }).catch(() => {
      ElMessage.info("您可以继续使用本地图片预览功能，但无法保存到服务器");
    });
    const reader = new FileReader();
    reader.onload = (e) => {
      if (callback && e.target?.result) {
        callback(e.target.result as string);
      }
    };
    reader.readAsDataURL(file);
    return;
  }
  const loading = ElLoading.service({
    lock: true,
    text: "图片上传中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  uploadImage(file)
    .then((response: any) => {
      if (response.code === 0 || response.code === 200) {
        const imageData = response.data as UploadImageResponse;
        const imageId = imageData.id;
        return feedbackImage(imageId).then((feedbackResponse) => {
          return { response: feedbackResponse, imageId };
        });
      } else {
        if (response.code === 401) {
          ElMessageBox.confirm("您的登录已过期，请重新登录。", "登录提示", {
            confirmButtonText: "去登录",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            localStorage.removeItem("token");
            localStorage.setItem("redirectAfterLogin", router.currentRoute.value.fullPath);
            router.push("/login");
          });
          return Promise.reject(new Error("login_required"));
        }
        throw new Error(response.msg || "上传失败");
      }
    })
    .then((result: any) => {
      if (!result) return;
      const { response, imageId } = result;
      if (response.code === 0 || response.code === 200) {
        const imageUrl = response.data;
        if (callback) callback(imageUrl, imageId);
        ElMessage.success("图片上传成功");
      } else {
        throw new Error(response.msg || "获取图片地址失败");
      }
    })
    .catch((error: any) => {
      if (error.message === "login_required") {
        return;
      }
      ElMessage.error({
        message: "图片上传失败: " + (error.message || "未知错误"),
        duration: 5000,
      });
    })
    .then(() => {
      loading.close();
    });
}

// 编辑弹窗关闭
const closeEditDialogMain = () => {
  showEditDialogMain.value = false;
  editModalVisible.value = false;
};

const closeEditDialogReference = () => {
  showEditDialogReference.value = false;
  editModalVisible.value = false;
};

// 预览弹窗取消处理
const cancelMainPreview = () => {
  showPreviewDialogMain.value = false;
  uploadModalVisible.value = false;
  // 清空文件输入框
  if (fileInputMain.value) {
    fileInputMain.value.value = '';
  }
  selectedFileMain.value = null;
  previewImageMain.value = '';
};

const cancelReferencePreview = () => {
  showPreviewDialogReference.value = false;
  uploadModalVisible.value = false;
  // 清空文件输入框
  if (fileInputReference.value) {
    fileInputReference.value.value = '';
  }
  selectedFileReference.value = null;
  previewImageReference.value = '';
};

// 编辑完成后关闭弹窗
const handleMainImageEdited = (editedImageUrl: string, imageId?: number | string) => {
  mainImage.value = editedImageUrl;
  if (imageId !== undefined) {
    mainImageId.value = typeof imageId === 'number' ? imageId : parseInt(imageId as string, 10);
    mainImageName.value = imageId.toString();
  }
  showEditDialogMain.value = false;
};

const handleReferenceImageEdited = (editedImageUrl: string, imageId?: number | string) => {
  referenceImage.value = editedImageUrl;
  if (imageId !== undefined) {
    referenceImageId.value = typeof imageId === 'number' ? imageId : parseInt(imageId as string, 10);
    referenceImageName.value = imageId.toString();
  }
  showEditDialogReference.value = false;
};

// 处理结果图选择
const handleResultSelected = () => {
  console.log("用户选择了一张结果图片");
};

// 退出结果查看模式
const exitResultsView = () => {
  console.log("退出结果查看模式");
  isViewingResults.value = false;
  generatedImages.value = [];
  
  // 确保其他状态也被重置
  isEditingMainImage.value = false;
  isEditingReferenceImage.value = false;
  editModalVisible.value = false;
  uploadModalVisible.value = false;
  
  // 如果resultsWorkspaceRef存在，也重置它的状态
  if (resultsWorkspaceRef.value) {
    try {
      resultsWorkspaceRef.value.isViewingResults = false;
      resultsWorkspaceRef.value.resultImages = [];
    } catch (e) {
      console.error("重置resultsWorkspaceRef状态失败:", e);
    }
  }
};

// 处理生成按钮点击
const handleGenerate = async () => {
  if (!canGenerate.value) return;

  // 验证用户登录
  if (!isUserLoggedIn()) {
    ElMessageBox.confirm(
      "您需要登录才能使用生成功能。是否现在登录？",
      "未登录提示",
      {
        confirmButtonText: "去登录",
        cancelButtonText: "取消",
        type: "warning",
      }
    ).then(() => {
      localStorage.setItem(
        "redirectAfterLogin",
        router.currentRoute.value.fullPath
      );
      router.push("/login");
    });
    return;
  }

  // 验证图片ID是否存在
  if (mainImageId.value === null || referenceImageId.value === null) {
    ElMessage.warning("请先将图片上传至服务器");
    return;
  }

  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "正在生成图片，请稍候...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    console.log("使用的图片ID:", {
      鞋面图ID: mainImageId.value,
      鞋底图ID: referenceImageId.value,
      蒙版状态: maskStates.value,
    });

    // 准备请求参数
    const requestData: XdhhRequest = {
      majorId: mainImageId.value,
      minorId: referenceImageId.value,
      maskStates: maskStates.value,
    };

    // 发送请求
    console.log("发送鞋底互换请求:", requestData);
    const response = await xdhh(requestData);
    console.log("收到鞋底互换响应:", response);

    // 接受 code 0 和 code 200 都表示成功
    if (response.code === 0 || response.code === 200) {
      // 兼容不同的返回格式
      let viewUrls: string[] = [];
      
      if (response.data && response.data.viewUrls) {
        // 标准格式：{code: 0/200, msg: "", data: {promptId: "", viewUrls: [...]}}
        viewUrls = response.data.viewUrls;
        console.log("从response.data.viewUrls获取到图片链接:", viewUrls);
      } else if (response.viewUrls) {
        // 直接包含viewUrls的格式：{code: 0/200, msg: "", viewUrls: [...]}
        viewUrls = response.viewUrls;
        console.log("从response.viewUrls获取到图片链接:", viewUrls);
      } else {
        console.error("找不到生成的图片链接");
        throw new Error('找不到生成的图片链接');
      }

      // 保存生成的图片URL
      generatedImages.value = viewUrls;
      console.log("设置generatedImages:", generatedImages.value);

      // 显示结果
      if (generatedImages.value.length > 0) {
        // 重置其他状态
        isEditingMainImage.value = false;
        isEditingReferenceImage.value = false;
        editModalVisible.value = false;
        uploadModalVisible.value = false;
        
        // 设置查看结果状态
        console.log("设置isViewingResults为true");
        isViewingResults.value = true;

        // 如果有resultsWorkspaceRef，调用其showResults方法
        if (resultsWorkspaceRef.value) {
          try {
            console.log('准备调用showResults方法，参数:', generatedImages.value);
            
            // 添加crossOrigin属性并预加载图片
            const preloadPromises = generatedImages.value.map(url => {
              return new Promise<boolean>((resolve) => {
                const img = new Image();
                img.crossOrigin = 'anonymous'; // 添加跨域支持
                
                img.onload = () => {
                  console.log(`图片预加载成功: ${url.substring(0, 50)}...`);
                  resolve(true);
                };
                
                img.onerror = (err) => {
                  console.error(`图片预加载失败: ${url.substring(0, 50)}...`, err);
                  resolve(false);
                };
                
                // 如果URL是http/https开头，添加缓存破坏参数
                if (url.startsWith('http')) {
                  img.src = `${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`;
                } else {
                  img.src = url;
                }
              });
            });
            
            // 等待所有图片预加载完成
            Promise.all(preloadPromises).then(results => {
              // 过滤掉加载失败的图片URL
              const validImages = generatedImages.value.filter((_, i) => results[i]);
              
              if (validImages.length === 0) {
                console.error('所有图片预加载失败');
                ElMessage.error('图片加载失败，请重试');
                return;
              }
              
              if (validImages.length < generatedImages.value.length) {
                console.warn(`部分图片加载失败: 成功 ${validImages.length}/${generatedImages.value.length}`);
                ElMessage.warning(`部分图片加载失败，仅显示 ${validImages.length} 张图片`);
              }
              
              // 更新有效的图片列表
              generatedImages.value = validImages;
              console.log("更新后的generatedImages:", generatedImages.value);
              
              // 调用showResults方法显示图片
              resultsWorkspaceRef.value.showResults(generatedImages.value).then(() => {
                console.log('showResults方法调用成功');
              }).catch(error => {
                console.error('调用showResults方法失败:', error);
                // 手动更新组件状态作为备选方案
                console.log("出现异常，手动设置组件状态");
                resultsWorkspaceRef.value.isViewingResults = true;
                resultsWorkspaceRef.value.resultImages = generatedImages.value;
              });
            });
            
          } catch (e) {
            console.error("调用showResults方法失败:", e);
            // 直接更新组件状态作为备选方案
            console.log("出现异常，手动设置组件状态");
            resultsWorkspaceRef.value.isViewingResults = true;
            resultsWorkspaceRef.value.resultImages = generatedImages.value;
          }
        } else {
          console.error("resultsWorkspaceRef不存在");
        }

        ElMessage.success("鞋底互换生成成功");
      } else {
        ElMessage.warning("生成成功但未获得图片");
      }
    } else {
      // 处理特定的错误码
      if (response.code === 1013) {
        throw new Error("请先选择需要更改的区域！");
      } else {
        throw new Error(response.msg || "生成图片失败");
      }
    }
  } catch (error: any) {
    console.error("鞋底互换失败:", error);
    // 显示错误信息，如果是code 1013的特定处理
    ElMessage.error("生成失败: " + (error.message || "未知错误"));
  } finally {
    loadingInstance.close();
  }
};

// 显示标记可选区域选项
const showSelectionOptions = (step: number) => {
  // 保存当前步骤
  currentMarkStep.value = step;
  
  // 确保当前处于正确的步骤
  if (currentStep.value !== step) {
    setStep(step);
  }
  
  // 显示选项对话框
  showSelectionDialog.value = true;
};

// 处理选项选择
const handleSelectOption = (option: string) => {
  showSelectionDialog.value = false;
  
  // 设置编辑状态
  if (currentMarkStep.value === 1) {
    isEditingMainImage.value = true;
    isEditingReferenceImage.value = false;
  } else {
    isEditingMainImage.value = false;
    isEditingReferenceImage.value = true;
  }
  
  // 使用setTimeout确保DOM更新后调用工具函数
  setTimeout(() => {
    // 根据当前步骤选择对应的工作区组件
    const workspaceRef =
      currentMarkStep.value === 1
        ? mainImageWorkspaceRef.value
        : referenceImageWorkspaceRef.value;

    if (workspaceRef) {
      // 根据选项打开不同工具
      if (option === 'brush') {
        // 涂抹选区 - 使用mask工具
        workspaceRef.openToolModal('mask');
      } else if (option === 'smart') {
        // 智能选区 - 使用smartSelect工具
        workspaceRef.selectTool('smartSelect');
      }
    }
  }, 100);
};

// 添加处理标记区域的函数
const handleMarkArea = (step: number) => {
  // 确保当前处于正确的步骤
  if (currentStep.value !== step) {
    setStep(step);
  }
  
  // 设置编辑状态
  if (step === 1) {
    isEditingMainImage.value = true;
    isEditingReferenceImage.value = false;
  } else {
    isEditingMainImage.value = false;
    isEditingReferenceImage.value = true;
  }

  // 使用setTimeout确保DOM更新后调用工具函数
  setTimeout(() => {
    // 根据当前步骤选择对应的工作区组件
    const workspaceRef =
      step === 1
        ? mainImageWorkspaceRef.value
        : referenceImageWorkspaceRef.value;

    // 调用工作区的标记可选功能
    if (workspaceRef) {
      workspaceRef.openToolModal('mask');
    }
  }, 100); // 给DOM一点时间更新
};

// 添加完成编辑的函数
const completeStep = (step: number) => {
  if (step === 1 && mainImage.value) {
    // 如果当前在编辑主图，则完成编辑并进入下一步
    isEditingMainImage.value = false;
    currentStep.value = 2;
  } else if (step === 2 && referenceImage.value) {
    // 如果当前在编辑参考图，则完成编辑
    isEditingReferenceImage.value = false;
  }
};
</script>

<style scoped>
.sole-fusion-container {
  width: 100%;
  min-height: 100vh;
  background: transparent;
  color: #fff;
  padding: 20px;
  position: relative;
  margin-left: 80px;
}

.sole-fusion-container::before {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("@/assets/bg.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  z-index: -1;
}

.fusion-content {
  display: flex;
  gap: 20px;
  min-height: calc(100vh - 40px);
  height: auto;
  padding: 20px;
  max-width: calc(100vw - 100px);
  position: relative;
  z-index: 2;
}

.left-panel {
  width: 270px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 10px;
  backdrop-filter: blur(10px);
  overflow-y: auto;
  max-height: 100%;
}

.work-area {
  flex: 1;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.right-panel {
  width: 280px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 10px;
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 100%;
  overflow-y: auto;
}

.step-section {
  margin-bottom: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.active-step {
  box-shadow: 0 0 10px rgba(0, 163, 255, 0.3);
  background: rgba(0, 163, 255, 0.05);
}

.completed-step .step-title {
  color: rgba(255, 255, 255, 0.7);
}

.disabled-step {
  opacity: 0.6;
  pointer-events: none;
}

.step-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  padding: 6px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.step-header:hover {
  background: rgba(255, 255, 255, 0.1);
}

.step-title {
  color: #c8ad7f;
  font-weight: bold;
}

.step-desc {
  font-size: 16px;
  color: #fff;
}

.step-status {
  margin-left: auto;
  color: #00FF00;
}

.upload-section {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  padding: 10px;
}

.image-preview {
  width: 100%;
  aspect-ratio: 4/3;
  border-radius: 6px;
  border: 1px dashed transparent;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.2);
}

.image-preview:hover {
  border-color: transparent;
  background: rgba(0, 163, 255, 0.1);
}

.usage-guide {
  color: #c8ad7f;
  padding: 10px;
}

.usage-guide ol {
  padding-left: 15px;
}

.usage-guide li {
  margin-bottom: 8px;
}

.generate-btn {
  width: 100%;
  height: 40px;
  background: linear-gradient(90deg, #c8ad7f 0%, #ffe7b2 100%);
  border: none;
  border-radius: 20px;
  font-size: 16px;
  margin-top: 500px;
  color: #fff;
  font-weight: bold;
  box-shadow: 0 2px 8px #c8ad7f33;
  transition: background 0.2s, color 0.2s;
}
.generate-btn:disabled {
  background: linear-gradient(90deg, #e0cfa0 0%, #f5e6c3 100%);
  opacity: 0.7;
  color: #fff;
}
.generate-btn:hover:not(:disabled) {
  background: linear-gradient(90deg, #ffe7b2 0%, #c8ad7f 100%);
  color: #c8ad7f;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: rgba(255, 255, 255, 0.7);
}

.loading-icon {
  font-size: 36px;
  animation: rotate 1.5s linear infinite;
  margin-bottom: 16px;
}

.image-workspace-container {
  width: 100%;
  height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;

}

.empty-workspace {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: rgba(255, 255, 255, 0.5);
}

.empty-message .el-icon {
  font-size: 48px;
}

.empty-message p {
  font-size: 16px;
  margin: 0;
}

:deep(.el-collapse) {
  border: none;
  background: transparent;
}

:deep(.el-collapse-item__header) {
  background: transparent;
  color: #c8ad7f;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-collapse-item__content) {
  background: transparent;
  color: #fff;
  padding: 0;
}

:deep(.el-radio) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-radio__label) {
  color: white;
}

:deep(.el-upload-dragger) {
  background-color: transparent;
  border: none;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

:deep(.el-upload-dragger:hover) {
  background-color: transparent;
  border-color: transparent;
}

:deep(.el-upload-dragger:hover .el-icon) {
  color: #00a3ff;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 添加标记区域的样式 */
.mark-area {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 20px;
  background: rgba(0, 163, 255, 0.1);
  border: 1px solid rgba(0, 163, 255, 0.3);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 15px;
  font-size: 14px;
  font-weight: 500;
  color: #c8ad7f;;
}

.mark-area:hover {
  background: rgba(0, 163, 255, 0.2);
  border-color: rgba(0, 163, 255, 0.5);
  transform: translateY(-2px);
}

.mark-area .el-icon {
  font-size: 16px;
  color: #c8ad7f; ;
}

.preview-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.change-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.change-overlay .el-icon {
  font-size: 24px;
  color: white;
  margin-bottom: 8px;
}

.change-overlay span {
  color: white;
  font-size: 14px;
}

.preview-container:hover .change-overlay {
  opacity: 1;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.6);
}

.upload-placeholder .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.upload-placeholder span {
  font-size: 14px;
}

.hidden-upload {
  display: none;
}

.nav-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.step-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.instructions-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.instructions-content {
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10px);
  border-radius: 10px;
  padding: 15px 20px;
  max-width: 500px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.instructions-content h3 {
  color: #c8ad7f;
  font-size: 18px;
  margin-bottom: 12px;
  text-align: center;
}

.instructions-content ol {
  list-style: none;
  padding: 0;
  margin: 0;
  counter-reset: instruction-counter;
}

.instructions-content li {
  color: #c8ad7f;
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 10px;
  padding-left: 28px;
  position: relative;
  counter-increment: instruction-counter;
}

.instructions-content li::before {
  content: counter(instruction-counter);
  position: absolute;
  left: 0;
  top: 0;
  width: 20px;
  height: 20px;
  background: #c8ad7f;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: white;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border: 2px solid #c8ad7f;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(200, 173, 127, 0.15);
  background: rgba(30, 30, 30, 0.98);
  color: #fff;
}

.upload-modal-content {
  padding: 20px 0;
}

.upload-area {
  width: 80%;
  height: 400px;
  border: 2px dashed transparent;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.03);
  margin: 0 auto;
}

.upload-area:hover {
  border-color: transparent;
}

.file-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.file-preview .preview-img {
  max-width: 95%;
  max-height: 90%;
  object-fit: contain;
  border: none;
  border-radius: 4px;
  margin-bottom: 10px;
}

.file-info {
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
}

.file-info p {
  margin: 2px 0;
}

.upload-tip {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 编辑弹框样式 */
.edit-dialog :deep(.el-dialog) {
  border: 2px solid #c8ad7f;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(200, 173, 127, 0.15);
  background: rgba(30, 30, 30, 0.98);
  color: #fff;
  max-width: 95vw;
  max-height: 95vh;
}

.edit-modal-content {
  height: 60vh;
  overflow: hidden;
}

.edit-modal-content .image-workspace-container {
  height: 100%;
  width: 100%;
}


</style>
